package com.example.mall_image_server.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

@Component
public class FileUploadUtils {
    private static String[] limitImageTypes;
    private static Double limitImageSize;

    @Value("${upload.image.image-limit-typys}")
    private void setLimitImageTypes(String[] images) {
        FileUploadUtils.limitImageTypes = images;
    }

    @Value("${upload.image.image-limit-size}")
    public void setLimitImageSize(Double size) {
        FileUploadUtils.limitImageSize = size;
    }

    /**
     * 图片限制-校验
     * @param file
     * @return
     */
    public static boolean checkImage(MultipartFile file) {
        if (file.isEmpty()) {
            System.out.println("文件为空");
            // throw new RuntimeException("文件为空");
            return false;
        }
        if (!FileUploadUtils.checkImageType(FileUploadUtils.limitImageTypes, file.getContentType())) {
            System.out.println("不满足图片格式: " + FileUploadUtils.limitImageTypes.toString());
            // throw new RuntimeException("不满足图片格式: " + FileUploadUtils.limitImageTypes.toString());
            return false;
        }
        if (file.getSize() > FileUploadUtils.limitImageSize) {
            System.out.println("图片过大, 不能超过: " + FileUploadUtils.limitImageSize + "k");
            // throw new RuntimeException("图片过大, 不能超过: " + FileUploadUtils.limitImageSize + "k");
            return false;
        }
        return true;
    }

    /**
     * 校验图片
     * @param types
     * @param type
     * @return
     */
    private static boolean checkImageType(String[] types, String type) {
        boolean exists = new HashSet<>(Arrays.asList(types)).contains(type);
        // System.out.println("满足图片类型吗 ? " + exists);
        return exists;
    }
}
